<!-- 
 * Copyright (c) 2021-2025 申菱环境 All Rights Reserved
 * 项目名称：申菱物联平台
 * 模块名称：服务工单
 * 功能名称：工单详情
 * author : huzhiqi
 * date   : 2022/7/14 10:20
 -->
<template>
  <div class="customerinfo-container flex flex-row min-w-full">
    <div class="flex-1 pt-7 pr-7 border-0 border-r border-gray-200 border-solid">
      <a-skeleton :loading="!showOrderInfoFlag" avatar :paragraph="{ rows: 10 }" active>
        <a-descriptions
          :title="t('aiot.serviceOrder.customerInfo')"
          :label-style="{ width: '130px', color: ' #7B879A' }"
          :column="1"
          :colon="false"
          class="pt-4"
        >
          <template #extra>
            <span
              v-if="orderInfo.serviceOrderCode && orderInfo.serviceOrderId"
              class="cursor-pointer text-color-secondary text-base"
              @click="viewApplyDetailFn"
              >申请详情 <Icon type="icon-you" class="pl-2"
            /></span>
          </template>
          <a-descriptions-item v-for="(item, index) in customerArr" :key="'base' + index" :label="item.label"
            >{{ orderInfo[item.value] || "--" }}
            <span v-if="item.value === 'contactsPerson'"
              >({{ item.mutilKey ? orderInfo[item.mutilKey] || "--" : "--" }})</span
            ></a-descriptions-item
          >
        </a-descriptions>
        <a-descriptions
          :title="t('aiot.serviceOrder.repairInfo')"
          :label-style="{ width: '130px', color: ' #7B879A' }"
          :column="1"
          :colon="false"
          class="pt-4"
        >
          <a-descriptions-item>
            <div class="flex flex-row items-center">
              <!-- <img class="w-24 h-24 mr-4" :src="deviceimg" alt="" srcset="" /> -->
              <a-image class="w-24 h-24 mr-4" :src="deviceimg" :fallback="emptyImg"></a-image>
              <div class="flex flex-col">
                <KeyValue
                  :label="t('aiot.equpiment.equipmentName')"
                  :value="orderInfo?.equipmentName || '--'"
                  class="mt-3 cursor-pointer"
                  value-class="!text-color-active"
                  @self-click="viewEquipmentInfo"
                />
                <KeyValue :label="t('aiot.equpiment.equipmentNo')" :value="orderInfo?.equipmentVo?.equipmentNo" />
                <KeyValue :label="t('aiot.equpiment.location')" :value="orderInfo?.equipmentVo?.location" />
              </div>
            </div>
          </a-descriptions-item>
          <a-descriptions-item v-for="(item, index) in repairArr" :key="'contract' + index" :label="item.label">{{
            orderInfo[item.value] || "--"
          }}</a-descriptions-item>
        </a-descriptions>
        <a-descriptions
          :label-style="{ width: '130px', color: ' #7B879A' }"
          :column="1"
          :colon="false"
          layout="vertical"
        >
          <a-descriptions-item :label="t('aiot.serviceWorkOrderInfo.faultImgs')">
            <!-- <div v-if="faultImgs.length > 0" class="flex flex-row items-center flex-wrap">
              <img v-for="(item, index) in faultImgs" :key="index + 'faultImg'" class="w-24 h-24 mr-4" :src="item" />
            </div> -->
            <a-image-preview-group v-if="faultImgs && faultImgs.length > 0" class="flex flex-row">
              <a-image
                v-for="(item, index) of faultImgs"
                :key="'images' + index"
                :fallback="emptyImg"
                width="84px"
                height="84px"
                :src="item"
              />
            </a-image-preview-group>
            <span v-else>--</span>
          </a-descriptions-item>
        </a-descriptions>
      </a-skeleton>
    </div>
    <div class="flex-1 p-7 pr-12 border-0 border-r border-gray-200 border-solid">
      <a-skeleton :loading="!showOrderInfoFlag" avatar :paragraph="{ rows: 12 }" active>
        <a-descriptions
          :title="t('aiot.serviceOrder.orderInfo')"
          :label-style="{ width: '130px', color: ' #7B879A' }"
          :column="1"
          :colon="false"
          class="pt-4"
        >
          <a-descriptions-item
            v-for="(item, index) in workOrderArr"
            :key="'base' + index"
            :label="item.label"
            class="relative"
            :content-style="{ width: '120px' }"
            >{{ getValuePro(item) }}
          </a-descriptions-item>
        </a-descriptions>
        <!-- 待派单没有派单信息 -->
        <a-descriptions
          v-if="orderInfo.workOrderState !== 'DISPATCH' && dispatchShow"
          :label-style="{ width: '130px', color: ' #7B879A' }"
          :column="1"
          :colon="false"
        >
          <a-descriptions-item
            v-for="(item, index) in dispatchArr"
            :key="'base' + index"
            :label="item.label"
            class="relative"
            >{{ getValuePro(item) }}
            <span
              v-if="item.value === 'helperUserName' && orderInfo.updateHelperFlag === 1"
              class="text-color-active cursor-pointer ml-4 absolute bg-white"
              style="right: -1.8rem"
              @click="handleUpdateWorkOrder"
              >选择</span
            >
            <span
              v-if="item.value === 'plannTime' && orderInfo.updatePlannTimeFlag === 1"
              class="text-color-active cursor-pointer ml-4 absolute"
              style="right: -1.8rem"
              @click="handleUpdatePlanTime"
              >修改计划时间</span
            >
          </a-descriptions-item>
        </a-descriptions>
        <div class="service-progress">
          <div class="ant-descriptions-title mb-6"> {{ t("aiot.serviceWorkOrderInfo.serviceProgress") }} </div>
          <a-timeline>
            <a-timeline-item v-for="(item, index) in recordArr" :key="item.workOrderRecordsId">
              <template #dot>
                <Icon
                  :type="stepStatusIcon[item.workOrderState || 0]"
                  class="!text-color-secondary text-2xl"
                  :class="
                    index === 0 && orderInfo.workOrderState !== 'CANCEL'
                      ? ' !text-color-success'
                      : orderInfo.workOrderState === 'CANCEL' && index === 0
                      ? '!text-color-warn'
                      : null
                  "
                />
              </template>
              <div>
                <div class="flex flex-row items-center">
                  <div
                    class="text-color-secondary"
                    :class="
                      index === 0 && orderInfo.workOrderState !== 'CANCEL'
                        ? ' !text-color-success'
                        : orderInfo.workOrderState === 'CANCEL' && index === 0
                        ? ' !text-color-warn'
                        : null
                    "
                    >{{ item.workOrderStateName }}</div
                  >
                  <div class="text-sm text-color-secondary pl-2">{{ item.recordTime }}</div>
                </div>
                <div class="text-color-secondary text-xs mt-2" :class="index === 0 ? ' !text-color-main' : null">
                  {{ item.recordContentDetailed }}
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>
      </a-skeleton>
    </div>
    <div class="flex-1 p-7 pr-12 border-0 border-r border-gray-200 border-solid">
      <a-skeleton :loading="!showOrderInfoFlag" avatar :paragraph="{ rows: 16 }" active>
        <a-descriptions
          v-if="signInfoShow"
          :title="t('aiot.serviceWorkOrderInfo.signinInfo')"
          :label-style="{ width: '130px', color: ' #7B879A' }"
          :column="1"
          :colon="false"
          class="pt-4"
        >
          <a-descriptions-item v-for="(item, index) in signinArr" :key="'base' + index" :label="item.label">{{
            getValueForKey(item, "signinInfo")
          }}</a-descriptions-item>
        </a-descriptions>
        <a-descriptions
          v-if="constructionInfoShow"
          :title="t('aiot.serviceWorkOrderInfo.constructionInfo')"
          :label-style="{ width: '130px', color: ' #7B879A' }"
          :column="1"
          :colon="false"
          class="pt-4"
        >
          <a-descriptions-item v-for="(item, index) in constructionArr" :key="'base' + index" :label="item.label">{{
            getValueForKey(item, "constructionInfo")
          }}</a-descriptions-item>
        </a-descriptions>
        <a-descriptions
          v-if="constructionInfoShow"
          :label-style="{ width: '130px', color: ' #7B879A' }"
          :column="1"
          :colon="false"
          layout="vertical"
        >
          <a-descriptions-item :label="t('aiot.serviceWorkOrderInfo.constructionBeforeImages')">
            <a-image-preview-group
              v-if="constructionBeforeImages && constructionBeforeImages.length > 0"
              class="flex flex-row"
            >
              <a-image
                v-for="(item, index) of constructionBeforeImages"
                :key="'constructionBeforeImages' + index"
                :fallback="emptyImg"
                width="84px"
                height="84px"
                :src="item"
              />
            </a-image-preview-group>
            <span v-else>--</span>
          </a-descriptions-item>
          <a-descriptions-item :label="t('aiot.serviceWorkOrderInfo.constructionAfterImages')">
            <a-image-preview-group
              v-if="constructionAfterImages && constructionAfterImages.length > 0"
              class="flex flex-row"
            >
              <a-image
                v-for="(item, index) of constructionAfterImages"
                :key="'constructionAfterImages' + index"
                :fallback="emptyImg"
                width="84px"
                height="84px"
                :src="item"
              />
            </a-image-preview-group>
            <span v-else>--</span>
          </a-descriptions-item>
          <a-descriptions-item :label="t('aiot.serviceWorkOrderInfo.constructionAppendixs')">
            <a-image-preview-group
              v-if="constructionAppendixs && constructionAppendixs.length > 0"
              class="flex flex-row"
            >
              <a-image
                v-for="(item, index) of constructionAppendixs"
                :key="'constructionAppendixs' + index"
                :fallback="emptyImg"
                width="84px"
                height="84px"
                :src="item"
              />
            </a-image-preview-group>
            <span v-else>--</span>
          </a-descriptions-item>
        </a-descriptions>
        <a-descriptions
          v-if="completeInfoShow"
          :title="t('aiot.serviceWorkOrderInfo.completeWorkOrderInfo')"
          :label-style="{ width: '130px', color: ' #7B879A' }"
          :column="1"
          :colon="false"
          class="pt-4"
        >
          <a-descriptions-item v-for="(item, index) in completeArr" :key="'base' + index" :label="item.label">{{
            getValueForKey(item, "completeInfo")
          }}</a-descriptions-item>
        </a-descriptions>
        <a-descriptions
          v-if="completeInfoShow"
          :label-style="{ width: '130px', color: ' #7B879A' }"
          :column="1"
          :colon="false"
          layout="vertical"
        >
          <a-descriptions-item :label="t('aiot.serviceWorkOrderInfo.appendixsImgs')">
            <a-image-preview-group v-if="completedAppendix && completedAppendix.length > 0" class="flex flex-row">
              <a-image
                v-for="(item, index) of completedAppendix"
                :key="'completedAppendix' + index"
                :fallback="emptyImg"
                width="84px"
                height="84px"
                :src="item"
              />
            </a-image-preview-group>
            <span v-else>--</span>
          </a-descriptions-item>
        </a-descriptions>
      </a-skeleton>
    </div>
    <SelectHelpUsers v-model:options="helpUserOptions" v-model:helperUserIdsValue="helperUserIds" @ok="successFn" />
    <SelectPlanTime v-model:options="planTimeOptions" @ok="planTimeSuccessFn" />
    <ServiceApplyDetails
      v-model:visible="applyDetailVisible"
      :service-order-id="serviceOrderId"
      :get-container="getContainer"
    />
  </div>
</template>

<script lang="ts" setup>
import { isArray } from "lodash";
import { DEFAULT_IMG_BASE64_STR } from "/@/utils/file";
import { computed, ref, watch } from "vue";
import { OrderDetails, RecordItem, WorkOrderInfo } from "/@/api/aiot/serviceWorkOrder/models";
import { useI18n } from "/@/locales/useI18n";
import Icon from "/@/components/Icon.vue";
import { WorkOrdersOperations } from "/@/types/components";
import emptyImg from "/emptyImg.svg";
const { t } = useI18n();
const props = withDefaults(
  defineProps<{
    orderInfo: WorkOrderInfo;
    recordArr: Array<RecordItem>;
    orderDetails: OrderDetails;
    showOrderInfoFlag: boolean;
    workRoleType?: string;
    getContainer?: () => HTMLElement;
  }>(),
  {}
);
const faultImgs = ref<Array<string | undefined>>([]);
const completedAppendix = ref<Array<string | undefined>>([]);
const constructionBeforeImages = ref<Array<string | undefined>>([]);
const constructionAfterImages = ref<Array<string | undefined>>([]);
const constructionAppendixs = ref<Array<string | undefined>>([]);
const dispatchShow = ref<boolean>(false);
const workOrderId = ref<string>("");
const applyDetailVisible = ref<boolean>(false);
const projectId = ref<string>("");
const helperUserIds = ref<Array<string>>([]);
const helpUserOptions = ref<WorkOrdersOperations>();
const planTimeOptions = ref<WorkOrdersOperations>();
const serviceOrderId = computed(() => {
  return props.orderInfo.serviceOrderId || "";
});
const stepStatusIcon = {
  EVALUATED: "icon-yipingjia",
  FINISHED: "icon-yiwancheng",
  PROGRESS: "icon-jinhangzhong",
  EXECUTE: "icon-yijiedan",
  WAITING: "icon-yipaidan",
  DISPATCH: "icon-yichuangjian",
  CREATE: "icon-yishenqing",
  CANCEL: "icon-yiquxiao",
};
// 获取设备图片
const workOrderInfo = ref<WorkOrderInfo>();
const emits = defineEmits(["successFn"]);
watch(
  () => props.orderInfo,
  (val) => {
    workOrderInfo.value = JSON.parse(JSON.stringify(val));
    workOrderId.value = props.orderInfo.workOrderId as string;
    projectId.value = props.orderInfo.projectId as string;
    if (workOrderInfo.value) {
      workOrderInfo.value.helperUserName = props.orderInfo.workOrderOperationResponse?.helperUsers
        .map((item) => {
          return item.helperUserName + (item.helperUserPhone ? "(" + item.helperUserPhone + ")" : "");
        })
        .join("，");
      helperUserIds.value =
        props.orderInfo.workOrderOperationResponse?.helperUsers.map((item) => {
          return item.helperUserId;
        }) || [];
      dispatchShow.value =
        props.orderInfo.workOrderOperationResponse !== null &&
        props.orderInfo.workOrderOperationResponse?.workOrderId !== "";
    }
    faultImgs.value = props.orderInfo?.faultImages || [];
    constructionBeforeImages.value = props.orderDetails.constructionInfo.constructionBeforeImages || [];
    constructionAfterImages.value = props.orderDetails.constructionInfo.constructionAfterImages || [];
    constructionAppendixs.value = props.orderDetails.constructionInfo.constructionAppendixs || [];
    completedAppendix.value = props.orderDetails.completeInfo.completedAppendix || [];
  }
);
const deviceimg = computed(() => {
  let imgs: Array<string> = [];
  imgs = props.orderInfo.equipmentVo?.equipmentInfo?.equipmentPhotoList || [];
  return imgs[0] || emptyImg;
});
function viewEquipmentInfo() {
  const link = document.createElement("a"); // 创建a标签
  if (props.orderInfo?.equipmentVo) {
    link.href = `/#/equipmentDetail/${props.orderInfo?.equipmentVo.equipmentId}/overview`;
    link.target = "_blank";
    link.click();
  }
}
function successFn(userName) {
  if (workOrderInfo.value) {
    workOrderInfo.value.helperUserName = userName;
    emits("successFn");
  }
}
function planTimeSuccessFn(plannTime) {
  if (workOrderInfo.value) {
    workOrderInfo.value.plannTime = plannTime;
    emits("successFn");
  }
}
function getValuePro(item) {
  if (!workOrderInfo.value) return;
  if (item.mutilKey) {
    let prefix = "";
    let suffix = "";
    if (workOrderInfo.value[item.value]) {
      prefix = workOrderInfo.value[item.value];
    } else if (
      workOrderInfo.value.workOrderOperationResponse &&
      workOrderInfo.value.workOrderOperationResponse[item.value]
    ) {
      prefix = workOrderInfo.value.workOrderOperationResponse[item.value];
    } else {
      prefix = "--";
    }
    if (workOrderInfo.value[item.mutilKey]) {
      suffix = "（" + workOrderInfo.value[item.mutilKey] + "）";
    } else if (
      workOrderInfo.value.workOrderOperationResponse &&
      workOrderInfo.value.workOrderOperationResponse[item.mutilKey]
    ) {
      suffix = "（" + workOrderInfo.value.workOrderOperationResponse[item.mutilKey] + "）";
    }
    return prefix + suffix;
  } else {
    return (
      workOrderInfo.value[item.value] ||
      (workOrderInfo.value.workOrderOperationResponse
        ? workOrderInfo.value.workOrderOperationResponse[item.value]
        : "--") ||
      "--"
    );
  }
}

const signInfoShow = computed(() => {
  return props.orderDetails?.signinInfo.length > 0;
});
const constructionInfoShow = computed(() => {
  return Object.keys(props.orderDetails?.constructionInfo).length > 0;
});
const completeInfoShow = computed(() => {
  return Object.keys(props.orderDetails?.completeInfo).length > 0;
});
/**
 * @param item
 * @param key  "signinInfo": 签到信息 | "constructionInfo"： 施工信息 | "completeInfo"： 完工信息
 */
function getValueForKey(item, key: "signinInfo" | "constructionInfo" | "completeInfo") {
  if (isArray(props.orderDetails[key][item.value])) {
    return props.orderDetails[key][item.value].join(",");
  } else if (item.value === "completionSituation") {
    return (
      {
        RESOLVED: t("aiot.serviceOrderOperationMsg.resolved"),
        UNRESOLVED: t("aiot.serviceOrderOperationMsg.unresolved"),
      }[props.orderDetails[key][item.value]] || "--"
    );
  } else if (key === "signinInfo") {
    let length = props.orderDetails.signinInfo?.length - 1 || 0;
    return props.orderDetails.signinInfo?.length > 0 ? props.orderDetails[key][length][item.value] : "--";
  } else {
    return props.orderDetails[key][item.value] || "--";
  }
}
function handleUpdateWorkOrder() {
  helperUserIds.value =
    props.orderInfo.workOrderOperationResponse?.helperUsers.map((item) => {
      return item.helperUserId;
    }) || [];
  helpUserOptions.value = {
    workOrderId: props.orderInfo.workOrderId,
    projectId: props.orderInfo.projectId,
  };
}
function handleUpdatePlanTime() {
  planTimeOptions.value = {
    workOrderId: props.orderInfo.workOrderId,
    projectId: props.orderInfo.projectId,
  };
}

function viewApplyDetailFn() {
  console.info("申请详情");
  applyDetailVisible.value = true;
}
const customerArr = [
  { label: t("aiot.serviceWorkOrderInfo.projectName"), value: "projectName" },
  {
    label: t("aiot.serviceWorkOrderInfo.contactName"),
    value: "contactsPerson",
    type: "mutil",
    mutilKey: "contactsPhone",
  },
  { label: t("aiot.serviceWorkOrderInfo.address"), value: "address" },
  { label: "期望时间", value: "expectedTime" },
];
const repairArr = [
  { label: t("aiot.serviceWorkOrderInfo.equipmentFaultNumber"), value: "equipmentNum" },
  { label: t("aiot.serviceWorkOrderInfo.equipmentFaultTypeName"), value: "faultTypeName" },
  { label: t("aiot.serviceWorkOrderInfo.happenTime"), value: "happenTime" },
  { label: t("aiot.serviceWorkOrderInfo.description"), value: "descriptions" },
  // { label: "故障图片", value: "fax" },
];
const signinArr = [
  {
    label: t("aiot.serviceWorkOrderInfo.signInUserName"),
    value: "signInUserName",
    type: "mutil",
    mutilKey: "signInUserPhone",
  },
  { label: t("aiot.serviceWorkOrderInfo.signInTime"), value: "signInTime" },
  { label: t("aiot.serviceWorkOrderInfo.signInAddress"), value: "signInAddress" },
];
const constructionArr = [
  { label: t("aiot.serviceWorkOrderInfo.failureReasonName"), value: "failureReasonName" },
  { label: t("aiot.serviceWorkOrderInfo.maintenanceTypeName"), value: "maintenanceTypeName" },
  { label: t("aiot.serviceWorkOrderInfo.maintenanceContent"), value: "maintenanceContent" },
];
const completeArr = [
  { label: t("aiot.serviceWorkOrderInfo.completionSituation"), value: "completionSituation" },
  { label: t("aiot.serviceWorkOrderInfo.completedTime"), value: "completedTime" },
  { label: t("aiot.serviceWorkOrderInfo.completedRemarks"), value: "completedRemarks" },
];
const workOrderArr = [
  { label: t("aiot.serviceWorkOrderInfo.serviceOrderCode"), value: "workOrderCode" },
  { label: t("aiot.serviceWorkOrderInfo.workOrderTypeName"), value: "workOrderTypeName" },
  { label: t("aiot.serviceWorkOrderInfo.sponsor"), value: "sponsor", type: "mutil", mutilKey: "sponsorPhone" },
  { label: t("aiot.serviceWorkOrderInfo.sponsorTime"), value: "sponsorTime" },
];
const dispatchArr = [
  { label: t("aiot.serviceWorkOrderInfo.appoint"), value: "appoint", mutilKey: "appointPhone", type: "mutil" },
  { label: t("aiot.serviceWorkOrderInfo.appointTime"), value: "appointTime" },
  {
    label: t("aiot.serviceWorkOrderInfo.operationUserName"),
    value: "operationUserName",
    type: "mutil",
    mutilKey: "operationUserPhone",
  },
  {
    label: t("aiot.serviceWorkOrderInfo.helperUserName"),
    value: "helperUserName",
    type: "mutil",
    mutilKey: "helperUserPhone",
  },
  { label: t("aiot.serviceWorkOrderInfo.plannTime"), value: "plannTime" },
  { label: t("aiot.serviceWorkOrderInfo.opinion"), value: "opinion" },
];
</script>

<style lang="less" scoped>
:deep(.ant-image) {
  max-width: 24rem;
  max-height: 24rem;
  margin-right: 1rem;
  margin-bottom: 1rem;
}
:deep(.ant-descriptions-item-content) {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
</style>
